﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule.Objective;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.Persistent;


public partial class Objective_ObjectiveList : PageBase
{
    ObjectiveManager manager = new ObjectiveManager();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["objectiveinputtype"] = new DictionaryItemsManager().GetItemList(DictionaryEnum.ObjectiveInputType, MyStateManager.DomainID);
            ViewState["objectivetype"] = new DictionaryItemsManager().GetItemList(DictionaryEnum.ObjectiveType, MyStateManager.DomainID);
            ObjectiveBind();

        }
    }

    /// <summary>
    /// 数据绑定
    /// </summary>
    ///
    public void ObjectiveBind()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder("AND Name like '%%' ");
 
        GridPager1.DataSource = manager.SelectObjectiveList(MyStateManager.DomainID, sb.ToString());
        GridPager1.GridView = GridView1;
        GridPager1.BindData();
        GridPager1.Visible = GridView1.Rows.Count > 0;

        DetailsView1.ChangeMode(DetailsViewMode.Insert);
        DetailsView1.DataBind();
    }

    /// <summary>
    /// 编辑
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DetailsView1.ChangeMode(DetailsViewMode.Edit);
        DetailsView1.DataBind();
        
    }
    protected void DetailsView1_DataBound(object sender, EventArgs e)
    {
       

        CheckBox chk = DetailsView1.FindControl("chkValid") as CheckBox;
        DropDownList ddlType = DetailsView1.FindControl("ddl_type") as DropDownList;
        DropDownList ddl_kind = DetailsView1.FindControl("ddl_kind") as DropDownList;
        //HtmlInputText txtDate = DetailsView1.FindControl("txtDate") as HtmlInputText;
        //txtDate.Value = DateTime.Now.AddMonths(1).ToString("yyyy-MM");

        if (ViewState["objectiveinputtype"] != null)
            ddlType.DataSource = ViewState["objectiveinputtype"];
        else
            ddlType.DataSource = new DictionaryItemsManager().GetItemList(DictionaryEnum.ObjectiveInputType, MyStateManager.DomainID);
        ddlType.DataTextField = "NAME";
        ddlType.DataValueField = "CODE";
        ddlType.DataBind();
        if (ViewState["objectivetype"] != null)
        {
            ddl_kind.DataSource = ViewState["objectivetype"];
        }else
            ddl_kind.DataSource = new DictionaryItemsManager().GetItemList(DictionaryEnum.ObjectiveType, MyStateManager.DomainID);
        ddl_kind.DataTextField = "NAME";
        ddl_kind.DataValueField = "CODE";
        ddl_kind.DataBind();
        ddl_kind.Items.Insert(0, new ListItem("--请选择--",""));
        if (DetailsView1.DataItem == null)
        {
            chk.Checked = true;
        }
        else
        {
            Objective o=DetailsView1.DataItem as Objective;
           
          
            //DetailsView1.Rows[4].Visible = false;
            //DetailsView1.Rows[5].Visible = false;

            ddlType.SelectedValue = o.INPUTTYPE.ToString();
            ddl_kind.SelectedValue = o.OBJECTIVETYPE.ToString();
            ddl_kind.Enabled = false;
          
        }

       
    }

    /// <summary>
    /// 保存数据方法
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            Objective objective = null;
            string detailmsg = "";
            TextBox txtName = DetailsView1.FindControl("txtName") as TextBox;
            TextBox txtUnit = DetailsView1.FindControl("txtUnit") as TextBox;
            DropDownList ddlType = DetailsView1.FindControl("ddl_type") as DropDownList;

            HtmlInputText txtDate = DetailsView1.FindControl("txtDate") as HtmlInputText;
            TextBox txt_OBJECTIVE_DATA = DetailsView1.FindControl("txt_OBJECTIVE_DATA") as TextBox;
            DropDownList ddlKind = DetailsView1.FindControl("ddl_kind") as DropDownList;

           

            if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
            {
                objective = new Objective();
                objective.CREATETIME = Jumpton.SFA.Server.BusinessRule.BusinessLogic.GetDateTimeDecimal(DateTime.Now);
                //判断是否已经存在此代码
                //问题，当通过ExistsObjectiveType后台ObjectRow.Load查询数据多于一条，会抛出错误 throw new Exception("ObjectRow Load Count > 1");
                //需要tr    
                if (manager.ExistsObjectiveType(ddlKind.SelectedValue, MyStateManager.DomainID))
                {
                    ShowMessage("已存在此类型目标");
                    return;
                }

               
            }
            else
            {
              
                objective = manager.LoadForType(ddlType.SelectedValue, MyStateManager.DomainID);
               
                if (objective == null)
                {
                    ShowMessage("保存失败");
                    return;
                }
               
               
            }

            objective.Name = txtName.Text;
            objective.Unit = txtUnit.Text;
            objective.INPUTTYPE = int.Parse(ddlType.SelectedValue);
            CheckBox cbxValid = DetailsView1.FindControl("chkValid") as CheckBox;
            objective.OBJECTIVETYPE = int.Parse(ddlKind.SelectedValue);
            objective.Active = cbxValid.Checked;
            objective.DomainID = MyStateManager.DomainID;
            objective.LAST_UPDATER = MyStateManager.UserID.ToString();
            objective.LAST_UPDATE_TIME = Jumpton.SFA.Server.BusinessRule.BusinessLogic.GetDateTimeDecimal(DateTime.Now);

            string LogContent = "";

            if (objective.State==DataRowState.Added)
            {
                LogContent += "增加新的目标，" + txtName.Text + "的信息是：";
            }
            else
            {
                LogContent += objective.Name + "信息发生变动，变动后信息是：";
            }
            LogContent += "目标名称：" + objective.Name + "，";
            LogContent += "目标单位：" + objective.Unit + "，";
            LogContent += "目标类型：" + objective.INPUTTYPE + "，";
            LogContent += "有效：" + objective.Active;
            //string ObjectiveID = "";
            
            if (manager.Save(objective))
            {
                ShowMessage("保存成功", Request.RawUrl.ToString());
                //Objective o = manager.LoadObjective(objective.DomainID, objective.OBJECTIVETYPE.ToString());
                //if (o != null)
                //{
                //    ObjectiveID = o.ID.ToString();
                //    DataTable udt = new Jumpton.SFA.Server.BusinessRule.System.UserManager().getAllChildSalesByOrgID(MyStateManager.OrgID, MyStateManager.DomainID, true);

                //    Objective_Details odetils = null;
                   
                   
                //    foreach (DataRow dr in udt.Rows)
                //    {

                //        try
                //        {
                //            if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
                //            {
                //                odetils = new Objective_Details();
                //                odetils.CREATETIME = Jumpton.SFA.Server.BusinessRule.BusinessLogic.GetDateTimeDecimal(DateTime.Now);
                //                //判断是否已经存在此代码
                //                if (manager.ExistsObjectiveDeatils(dr["ID"].ToString(), txtDate.Value.Replace("-", ""), ddlKind.SelectedValue))
                //                {
                //                    detailmsg = " 已存在 部分" + txtDate.Value + "月份目标! ";
                //                    continue;

                //                }
                               

                //            }
                //            else
                //            {
                                

                //            }

                //            odetils.ObjectiveData = decimal.Parse(txt_OBJECTIVE_DATA.Text);

                //            odetils.YEARMONTH = txtDate.Value.Replace("-", "").Replace("/", "");
                //            odetils.OBJECTIVEID = int.Parse(ObjectiveID);
                            
                //            odetils.OBJECTID = dr["ID"].ToString();
                //            odetils.Active = cbxValid.Checked;
                //            odetils.DomainID = MyStateManager.DomainID;
                //            odetils.LAST_UPDATE = MyStateManager.UserID.ToString();
                //            odetils.LAST_UPDATE_TIME = objective.LAST_UPDATE_TIME;


                //            manager.Save(odetils);
                            
                //        }
                //        catch (Exception ee)
                //        {
                //            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
                //           Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION, this.MyStateManager.Name,
                //           this.MyStateManager.UserID, "目标添加明细 - 异常:" + ee.Message + detailmsg);
                //        }
                //    }


                //}
                //Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
                // Jumpton.SFA.Server.BusinessRule.System.LogType.Info_Change, this.MyStateManager.Name,
                // this.MyStateManager.UserID, LogContent);
                //if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
                //{
                //    if (detailmsg != "")
                //    {
                //        ShowMessage("保存成功,但"+detailmsg, Request.RawUrl.ToString());
                //    }
                //    else
                //    {
                //        ShowMessage("保存成功", Request.RawUrl.ToString());
                //    }
                    
                //}
                //else
                //{
                //    ShowMessage("修改成功", Request.RawUrl.ToString());
                   
                //}
            }
            else
            {
                ShowMessage("保存失败");
            }
          
           
        }
        catch (Exception ex)
        {
            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
                    Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION, this.MyStateManager.Name,
                    this.MyStateManager.UserID, "目标维护 - 异常:" + ex.Message);
        }
    }

   
  
  
    /// <summary>
    /// 新增方法
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        DetailsView1.ChangeMode(DetailsViewMode.Insert);
        DetailsView1.DataBind();
     
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        ObjectiveBind();
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string ID = e.CommandArgument.ToString();
        if (e.CommandName == "AddDetail")
        {
            Response.Redirect("ObjectiveDetailList.aspx?OID=" + ID);
        }
       
    }

    public string getObjectiveType(string v)
    {
        ObjectTable ot= null;
        if (ViewState["objectivetype"] != null)
        {
            ot = ViewState["objectivetype"] as ObjectTable;
        }
        else
        {
            ot = new DictionaryItemsManager().GetItemList(DictionaryEnum.ObjectiveType, MyStateManager.DomainID);
        }
         foreach (DictionaryItems d in ot)
         {
             if (d.Code == v)
             {
                 return d.Name;
             }
         }
         return "";
    }

    public string getObjectiveInputType(string v)
    {
        ObjectTable ot= null;
        if (ViewState["objectiveinputtype"] != null)
        {
            ot = ViewState["objectiveinputtype"] as ObjectTable;
        }
        else
        {
            ot = new DictionaryItemsManager().GetItemList(DictionaryEnum.ObjectiveInputType, MyStateManager.DomainID);
        }
         foreach (DictionaryItems d in ot)
         {
             if (d.Code == v)
             {
                 return d.Name;
             }
         }
         return "";
    }
}
